package com.viewpagerindicator.sample.fragents;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.viewpagerindicator.sample.GoodsListActivity;
import com.viewpagerindicator.sample.R;
import com.viewpagerindicator.sample.adapters.GoodsListAdapter;
import com.viewpagerindicator.sample.adapters.TypeListAdapter;
import com.viewpagerindicator.sample.beans.Goods;
import com.viewpagerindicator.sample.beans.GoodsType;
import com.viewpagerindicator.sample.util.URLs;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

public final class SecondFragment extends Fragment {
    private static final String KEY_CONTENT = "TestFragment:Content";

    public static SecondFragment newInstance(String content) {
        SecondFragment fragment = new SecondFragment();
        return fragment;
    }

    private String mContent = "???";
    ArrayList<GoodsType> goodsArrayList=new ArrayList<>();
    ArrayList<Goods> goodsList=new ArrayList<>();
    private ListView listView;
    private TypeListAdapter adapter;
    private View listviewBg; //列表试图
    private View progressingBg;//等待试图;
    private View errormsgBg;//错误试图;
    private EditText searchEditText;
    private View searchView;

    private View rootView=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
            mContent = savedInstanceState.getString(KEY_CONTENT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
            return rootView;
        }

        View view= inflater.inflate(R.layout.second_layout,container,false);
        listviewBg=  view.findViewById(R.id.list_bg);
        progressingBg=  view.findViewById(R.id.progress_bg);
        errormsgBg=  view.findViewById(R.id.errormsg_bg);
        searchEditText= (EditText) view.findViewById(R.id.search_goods);
        searchView=  view.findViewById(R.id.btn_search);

        listView= (ListView) view.findViewById(R.id.type_listview);
            adapter = new TypeListAdapter(getActivity(), R.layout.type_item, goodsArrayList);
            listView.setAdapter(adapter);

            errormsgBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showView(progressingBg);
                initData();
            }
            });
            searchView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search(searchEditText.getText().toString());
            }
            });
            searchEditText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    if (charSequence.length() == 0) {
                        showView(listviewBg);
                }
                }

                @Override
                public void afterTextChanged(Editable editable) {

                }
            });
            initData();
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                showView(progressingBg);
                Integer typeid= (Integer) view.getTag();
                toType(typeid.toString());
            }
        });
        return view;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(KEY_CONTENT, mContent);
    }
    /**
     * 获取商品
     * */
    public void initData(){
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(URLs.getTypes, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                //解析数据
                try {
                    List<GoodsType> temp = GoodsType.parseList(responseBody);
                    if (temp != null) {
                        goodsArrayList.clear();
                        goodsArrayList.addAll(temp);
                        adapter.notifyDataSetChanged();
                        showView(listviewBg);
                    }
                } catch (Exception e) {
                    Toast.makeText(getActivity(), getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    showView(errormsgBg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Toast.makeText(getActivity(), getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                showView(errormsgBg);
            }
        });
    }
    /**
     * 搜搜
     * */
    public void search(String keyword){
        searchEditText.setText(keyword);
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams requestParams = new RequestParams("keyword",keyword);
        showView(progressingBg);
        client.get(URLs.search, requestParams, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                //解析数据
                try {
                    List<Goods> temp = Goods.parseList(responseBody);
                    if (temp != null&&temp.size()>0) {
                        goodsList.clear();
                        goodsList.addAll(temp);
                        showView(listviewBg);
                        Intent intent=new Intent(getActivity(),GoodsListActivity.class);
                        intent.putExtra("goodslistjson", responseBody);
                        startActivity(intent);
                    }else{
                        Toast.makeText(getActivity(),getString(R.string.result_is_null),Toast.LENGTH_SHORT).show();
                        showView(errormsgBg);
                    }
                } catch (Exception e) {
                    Toast.makeText(getActivity(), getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    showView(errormsgBg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Toast.makeText(getActivity(), getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                showView(errormsgBg);
            }
        });
    }
    /**
     * 搜搜
     * */
    public void toType(String typeid){
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams requestParams = new RequestParams("typeid",typeid);
        showView(progressingBg);
        client.get(URLs.typegoogs, requestParams, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                //解析数据
                try {
                    List<Goods> temp = Goods.parseList(responseBody);
                    if (temp != null) {
                        goodsList.clear();
                        goodsList.addAll(temp);
                    }
                    Intent intent=new Intent(getActivity(),GoodsListActivity.class);
                    intent.putExtra("goodslistjson", responseBody);
                    startActivity(intent);
                    showView(listviewBg);
                } catch (Exception e) {
                    Toast.makeText(getActivity(), getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    showView(errormsgBg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Toast.makeText(getActivity(), getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                showView(errormsgBg);
            }
        });
    }
    /**
     * 显示指定的view
     * */
    public void showView(View viewToShow){
        listviewBg.setVisibility(View.GONE);
        progressingBg.setVisibility(View.GONE);
        errormsgBg.setVisibility(View.GONE);
        viewToShow.setVisibility(View.VISIBLE);
    }
}
